package top.lyc829.zzl_android.ui.profile;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayoutMediator;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.textview.badge.Badge;
import com.xuexiang.xui.widget.textview.badge.BadgeView;

import top.lyc829.zzl_android.R;
import top.lyc829.zzl_android.databinding.ProfileFragmentBinding;
import top.lyc829.zzl_android.logic.bean.FansNumberBean;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.ui.login.LoginActivity;
import top.lyc829.zzl_android.ui.main.LazyFragment;
import top.lyc829.zzl_android.ui.main.MainViewModel;
import top.lyc829.zzl_android.ui.message.MessageActivity;
import top.lyc829.zzl_android.ui.profile.edit_user_info.EditUserInfoActivity;
import top.lyc829.zzl_android.ui.profile.follow.FollowActivity;
import top.lyc829.zzl_android.ui.profile.user_dtc.collect.UserCollectFragment;
import top.lyc829.zzl_android.ui.profile.user_dtc.dynamic.UserDynamicFragment;
import top.lyc829.zzl_android.ui.profile.user_dtc.travels.UserTravelsFragment;
import top.lyc829.zzl_android.ui.profile.user_fans.FansActivity;
import top.lyc829.zzl_android.ui.profile.user_fans.UserFansFragment;
import top.lyc829.zzl_android.ui.setting.SettingActivity;

public class ProfileFragment extends LazyFragment {

    private ProfileViewModel mViewModel;
    private MainViewModel mainViewModel;
    private ProfileFragmentBinding binding;
    private ConcernedViewModel cViewModel;
    private UserFansNumberViewModel uViewModel;

    TitleBar.ImageAction imageAction;
    Badge badge;

    public static ProfileFragment newInstance() {
        return new ProfileFragment();
    }



    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = ProfileFragmentBinding.inflate(getLayoutInflater());
        return binding.getRoot();
        //return inflater.inflate(R.layout.profile_fragment, container, false);

    }



    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(ProfileViewModel.class);
        mainViewModel = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
        cViewModel=new ViewModelProvider(this).get(ConcernedViewModel.class);
        uViewModel=new ViewModelProvider(this).get(UserFansNumberViewModel.class);

        TitleBar.ActionList actions = new TitleBar.ActionList();
        imageAction = new TitleBar.ImageAction(R.drawable.ic_baseline_email_24) {
            @Override
            public void performAction(View view) {
                startActivity(new Intent(getActivity(), MessageActivity.class));
            }
        };
        actions.add(imageAction);
        actions.add(new TitleBar.ImageAction(R.drawable.ic_baseline_settings_24) {
            @Override
            public void performAction(View view) {
                startActivity(new Intent(getActivity(), SettingActivity.class));
            }
        });
        binding.mTitleBarProfile.disableLeftView().addActions(actions);

        badge = new BadgeView(getContext())
                .bindTarget(binding.mTitleBarProfile.getViewByAction(imageAction))
                .setBadgeGravity(Gravity.TOP | Gravity.END)
                .setExactMode(false)
                .setBadgeBackgroundColor(0xdfFFC364)
                .setGravityOffset(-3, 8, true)
                .setBadgePadding(1, true)
                .setBadgeNumber(0);

       // binding.easyIndicatorProfile.setTabTitles(new String[] {"动态", "游记", "收藏"});



        binding.mProfileCard.setOnClickListener(v -> {
            if (Utils.isLogin()) {
                // 传递对象到下一个activity
                if (mViewModel.getUserInfoBeanMutableLiveData().getValue() == null) {
                    return;
                }
                Intent intent = new Intent(getActivity(), EditUserInfoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("userInfo", mViewModel.getUserInfoBeanMutableLiveData().getValue());
                intent.putExtras(bundle);
                startActivity(intent);
            } else {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
            }

        });

        binding.tvGoLogin.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
        });

        binding.goUserFans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!Utils.isLogin())
                {
                    Utils.showToast("请先登录");
                    return;
                }
                Intent intent = new Intent(getActivity(), FansActivity.class);
                intent.putExtra("id",Utils.getUserId());
                startActivity(intent);
            }
        });
        binding.goFollowBase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!Utils.isLogin())
                {
                    Utils.showToast("请先登录");
                    return;
                }
                Intent intent = new Intent(getActivity(), FollowActivity.class);
                intent.putExtra("id",1);//跳转至指定页面
                intent.putExtra("na",Utils.getUserId());
                startActivity(intent);
            }

        });
        binding.goFollowTeam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!Utils.isLogin())
                {
                    Utils.showToast("请先登录");
                    return;
                }
                Intent intent = new Intent(getActivity(), FollowActivity.class);
                intent.putExtra("id",2);
                intent.putExtra("na",Utils.getUserId());
                startActivity(intent);
            }
        });

        binding.goFollowUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!Utils.isLogin())
                {
                    Utils.showToast("请先登录");
                    return;
                }
                Intent intent = new Intent(getActivity(), FollowActivity.class);
                intent.putExtra("id",0);
                intent.putExtra("na",Utils.getUserId());
                startActivity(intent);
            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();
        if (!Utils.isLogin()) {
            binding.tvGoLogin.setVisibility(View.VISIBLE);
            binding.genderTextView.setVisibility(View.INVISIBLE);
            binding.usernameTextView.setVisibility(View.INVISIBLE);
            binding.signatureTextView.setVisibility(View.INVISIBLE);
            binding.fansNumber.setVisibility(View.INVISIBLE);
            binding.followBaseNumber.setVisibility(View.INVISIBLE);
            binding.followUserNumber.setVisibility(View.INVISIBLE);
            binding.followTeamNumber.setVisibility(View.INVISIBLE);
            Glide.with(getContext())
                    .load(R.drawable.ic_avator_not_load)
                    .into(binding.headerImage);
        } else {

            mViewModel.getUserInfoBeanMutableLiveData().observe(getViewLifecycleOwner(), userInfoBean -> {
                // 将用户id也保存到sp中
                // Utils.insertToSp("user_id", userInfoBean.getId().toString());
                binding.tvGoLogin.setVisibility(View.INVISIBLE);
                binding.genderTextView.setVisibility(View.VISIBLE);
                binding.usernameTextView.setVisibility(View.VISIBLE);
                binding.signatureTextView.setVisibility(View.VISIBLE);
                Glide.with(getContext())
                        .load(userInfoBean.getAvatarUrl())
                        .into(binding.headerImage);
                binding.usernameTextView.setText(userInfoBean.getNickname());
                String gender = Utils.isStringEmpty(userInfoBean.getGender()) ? "未知" : userInfoBean.getGender();
                binding.genderTextView.setText(gender);
                String signature = Utils.isStringEmpty(userInfoBean.getSignature()) ? "这个人很神秘，什么也没写..." : userInfoBean.getSignature();
                binding.signatureTextView.setText(signature);
            });
            mViewModel.getUserInfo();

            cViewModel.getConcernedInfo(Utils.getUserId());
            cViewModel.getConcernedBeanMutableLiveData().observe(getViewLifecycleOwner(),concernedInfoBean -> {
                binding.followBaseNumber.setVisibility(View.VISIBLE);
                binding.followUserNumber.setVisibility(View.VISIBLE);
                binding.followTeamNumber.setVisibility(View.VISIBLE);
                binding.followUserNumber.setText(String.valueOf(concernedInfoBean.getRelation_user_num()));
                binding.followTeamNumber.setText(String.valueOf(concernedInfoBean.getRelation_team_num()));
                binding.followBaseNumber.setText(String.valueOf(concernedInfoBean.getRelation_base_num()));
            });

            uViewModel.getFansNumberInfo(Utils.getUserId());
            uViewModel.getFansNumberBeanMutableLivedata().observe(getViewLifecycleOwner(), integer->{

                binding.fansNumber.setVisibility(View.VISIBLE);
                binding.fansNumber.setText(String.valueOf(integer));
            });

        }

        //msgNumberService();
        mainViewModel.updateMsgNumber();
    }

    @Override
    public void lazyInit() {


        //“我的”页面的我的动态、游记、收藏
        ViewPager2 viewPage2 = binding.viewPage2;
        viewPage2.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                if (position == 0) {
                    return new UserDynamicFragment();
                } else if (position == 1) {
                    return new UserTravelsFragment();
                } else {
                    return new UserCollectFragment();
                }
            }

            @Override
            public int getItemCount() {
                return 3;
            }
        });

        TabLayoutMediator mediator = new TabLayoutMediator(binding.tabLayout2, viewPage2, ((tab, position) -> {
            if (position == 0) {
                tab.setText("动态");
            } else if (position == 1) {
                tab.setText("游记");
            } else if (position == 2) {
                tab.setText("收藏");
            }
        }));

        mediator.attach();



        msgNumberService();
    }

    private void msgNumberService() {
        // 观察消息个数
        mainViewModel.getMsgNumberLiveData().observe(getViewLifecycleOwner(), msgNumberBean -> {
            badge.setBadgeNumber(msgNumberBean.getTotalNum());
        });
    }

}